function [R2] = Partial_R2(Y, X, XX, Z, k1, k2)

%Regress X on Z and save fitted values
Xhat=Z*(inv(Z'*Z)*Z'*X);
%Regress endogenous xs on remaining xs and get residuals
Ytilde=Y-XX*(inv(XX'*XX)*XX'*Y);
%Regress Xhat element(s) for endogenous x on the remaining  elements and
%get the residuals
Yhat=Xhat(:,2:k1+1);
XXhat=[Xhat(:,1) Xhat(:,k1+2:k1+k2)];
Ybar=Yhat-XXhat*(inv(XXhat'*XXhat)*XXhat'*Yhat);
%Compute sample squared correlation coefficient b/w Ytilde and Ybar
R2=corr(Ytilde,Ybar)^2;
